import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'dart:developer' as developer;
import 'dart:async';
import '../../services/file_service.dart';
import 'preview_utils.dart';
import 'video_preview.dart';
import 'enhanced_image_preview.dart';
import 'document_preview.dart';
import 'generic_preview.dart';
import 'package:flutter/foundation.dart';
import 'dart:convert';
import 'enhanced_audio_preview.dart';

/// 文件预览主组件
/// 用于根据文件类型选择合适的预览组件
class FilePreviewWidget extends StatefulWidget {
  final int fileId;
  final String fileName;
  final String fileType;

  const FilePreviewWidget({
    Key? key,
    required this.fileId,
    required this.fileName,
    required this.fileType,
  }) : super(key: key);

  @override
  State<FilePreviewWidget> createState() => FilePreviewWidgetState();
}

class FilePreviewWidgetState extends State<FilePreviewWidget> {
  bool _isLoading = true;
  String? _previewUrl;
  String? _mimeType;
  String? _error;
  String? _fileName;
  String? _fileType;
  String? _extension;
  bool _directPreview = false;
  int? _fileSize;

  @override
  void initState() {
    super.initState();
    _loadPreview();
  }

  /// 加载文件预览
  Future<void> _loadPreview() async {
    try {
      // 清空之前的错误和状态
      setState(() {
        _error = null;
        _isLoading = true;
      });

      developer.log('开始加载预览，文件ID: ${widget.fileId}', name: 'FilePreviewWidget');

      // 添加超时处理
      final preview = await FileService.getFilePreview(widget.fileId).timeout(
        const Duration(seconds: 15),
        onTimeout: () {
          throw TimeoutException('获取预览信息超时，请检查网络连接后重试');
        },
      );

      developer.log('预览响应: $preview', name: 'FilePreviewWidget');

      // 检查URL是否有效
      if (preview.data?.url == null || preview.data!.url.isEmpty) {
        throw Exception('无效的预览地址');
      }

      // 确保文件类型正确
      String fileType = preview.data?.fileType ?? widget.fileType;
      // 如果文件类型为空或为other，尝试从文件名推断类型
      if (fileType.isEmpty || fileType == 'other') {
        final fileName = preview.data?.fileName ?? widget.fileName;
        if (fileName.contains('.')) {
          fileType = PreviewUtils.getFileTypeFromExtension(fileName);
        }
      }

      // 如果是图片类型的文件，强制设置为 'image'
      if (preview.data?.mimeType.startsWith('image/') == true) {
        fileType = 'image';
      }

      developer.log(
        '文件信息:\n'
        'URL: ${preview.data?.url}\n'
        'MIME类型: ${preview.data?.mimeType}\n'
        '文件类型: $fileType\n'
        '文件名: ${preview.data?.fileName}\n'
        '扩展名: ${preview.data?.extension}\n'
        '直接预览: ${preview.data?.directPreview}',
        name: 'FilePreviewWidget',
      );

      if (mounted) {
        setState(() {
          _previewUrl = preview.data?.url;
          _mimeType = preview.data?.mimeType;
          _fileName = preview.data?.fileName ?? widget.fileName;
          _fileType = fileType;
          _extension =
              preview.data?.extension ??
              (_fileName?.contains('.') == true
                  ? _fileName!.split('.').last.toLowerCase()
                  : null);
          _directPreview = preview.data?.directPreview ?? false;
          _fileSize = preview.data?.fileSize;
          _isLoading = false;
        });
      }

      developer.log(
        '预览状态更新:\n'
        '文件类型: $_fileType\n'
        '扩展名: $_extension\n'
        '直接预览: $_directPreview\n'
        'MIME类型: $_mimeType',
        name: 'FilePreviewWidget',
      );
    } catch (e, stack) {
      developer.log(
        '预览加载错误:\n'
        '错误: $e\n'
        '堆栈: $stack',
        name: 'FilePreviewWidget',
      );
      if (mounted) {
        setState(() {
          _error = _getErrorMessage(e);
          _isLoading = false;
        });
      }
    }
  }

  /// 获取友好的错误消息
  String _getErrorMessage(dynamic error) {
    if (error is TimeoutException) {
      return '获取预览信息超时，可能原因：\n'
          '1. 网络连接不稳定\n'
          '2. 服务器响应较慢\n'
          '请检查网络连接后重试';
    }

    final errorStr = error.toString();
    if (errorStr.contains('无效的预览地址')) {
      return '无法获取预览地址，请稍后重试';
    }
    if (errorStr.contains('SocketException')) {
      return '网络连接错误，请检查：\n'
          '1. 网络是否正常连接\n'
          '2. 是否可以访问服务器';
    }
    if (errorStr.contains('HttpException')) {
      return '网络请求错误，请稍后重试';
    }
    if (errorStr.contains('FormatException')) {
      return '数据格式错误，请联系技术支持';
    }

    // 如果是其他错误，限制显示长度
    if (errorStr.length > 100) {
      return '${errorStr.substring(0, 100)}...';
    }
    return errorStr;
  }

  /// 重新加载预览
  Future<void> reloadPreview({bool forceRefresh = true}) async {
    if (!mounted) return;

    setState(() {
      _isLoading = true;
      _error = null;
    });

    if (forceRefresh) {
      // 强制刷新预览URL
      try {
        await Future.delayed(const Duration(milliseconds: 300)); // 短暂延迟

        if (!mounted) return; // 延迟后检查mounted状态

        final preview = await FileService.getFilePreview(
          widget.fileId,
          forceRefresh: true,
        );

        if (!mounted) return; // 再次检查mounted状态

        setState(() {
          _previewUrl = preview.data?.url;
        });

        developer.log('已刷新预览URL: $_previewUrl', name: 'FilePreviewWidget');
      } catch (e) {
        developer.log('刷新预览URL出错: $e', name: 'FilePreviewWidget');

        if (!mounted) return; // 确保错误处理中也检查mounted状态

        setState(() {
          _error = _getErrorMessage(e);
          _isLoading = false;
        });
        return; // 出错时直接返回，不继续加载
      }
    }

    // 重新加载预览
    if (mounted) {
      _loadPreview();
    }
  }

  // 保留原来的_reloadPreview方法，但调用新的公开方法
  Future<void> _reloadPreview({bool forceRefresh = true}) async {
    if (!mounted) return; // 添加mounted检查
    return reloadPreview(forceRefresh: forceRefresh);
  }

  /// 构建预览内容
  Widget _buildPreviewContent() {
    if (_error != null) {
      return Center(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                _error!.contains('超时') || _error!.contains('网络')
                    ? Icons.wifi_off
                    : Icons.error_outline,
                color: Colors.red[300],
                size: 64,
              ),
              const SizedBox(height: 16),
              Text(
                _error!.contains('超时') || _error!.contains('网络')
                    ? '网络连接问题'
                    : '预览加载失败',
                style: TextStyle(
                  color: Colors.red[300],
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 8),
              Text(
                _error!,
                textAlign: TextAlign.center,
                style: const TextStyle(color: Colors.grey),
              ),
              const SizedBox(height: 16),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  ElevatedButton.icon(
                    onPressed: () => reloadPreview(forceRefresh: true),
                    icon: const Icon(Icons.refresh),
                    label: const Text('重试'),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Theme.of(context).primaryColor,
                      foregroundColor: Colors.white,
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      );
    }

    if (_isLoading) {
      return const Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: 16),
            Text('加载中...'),
          ],
        ),
      );
    }

    if (_previewUrl == null) {
      return const Center(child: Text('无法加载预览'));
    }

    developer.log(
      '构建预览组件:\n'
      '文件类型: $_fileType\n'
      'MIME类型: $_mimeType\n'
      'URL: $_previewUrl',
      name: 'FilePreviewWidget',
    );

    // 根据文件类型选择合适的预览组件
    switch (_fileType?.toLowerCase()) {
      case 'image':
      case 'photo':
        return EnhancedImagePreview(
          previewUrl: _previewUrl,
          fileName: _fileName,
          fileId: widget.fileId,
          onRetry: () => _reloadPreview(forceRefresh: false),
        );
      case 'video':
        return VideoPreview(
          previewUrl: _previewUrl,
          fileName: _fileName,
          onRetry: () => _reloadPreview(forceRefresh: false),
        );
      case 'audio':
        return EnhancedAudioPreview(
          previewUrl: _previewUrl,
          fileName: _fileName,
          extension: _extension,
          mimeType: _mimeType,
          fileSize: _fileSize,
          onReloadRequest:
              (forceRefresh) => _reloadPreview(forceRefresh: forceRefresh),
        );
      case 'document':
        return DocumentPreview(
          previewUrl: _previewUrl,
          fileName: _fileName,
          fileType: _fileType,
          extension: _extension,
          mimeType: _mimeType,
          fileSize: _fileSize,
          directPreview: _directPreview,
          onRetry: () => _reloadPreview(forceRefresh: false),
        );
      default:
        return GenericPreview(
          previewUrl: _previewUrl,
          fileName: _fileName,
          fileType: _fileType,
          extension: _extension,
          mimeType: _mimeType,
          fileSize: _fileSize,
          onRetry: () => _reloadPreview(forceRefresh: false),
        );
    }
  }

  @override
  Widget build(BuildContext context) {
    return _buildPreviewContent();
  }
}
